<template>
  <div class="account">
    <!--头部-->
    <div class="header">
      <img src="./header.png" alt="">
    </div>
    <div class="content-wrapper">
      <div class="input-wrapper">
        <div class="input-item border-1px">
          <input type="tel" class="input" v-model="phone" placeholder="输入手机号" maxlength="11">
        </div>
        <div class="input-item border-1px">
          <input type="tel" class="input" v-model="code" placeholder="输入验证码" maxlength="4">
          <div class="get-code" @click="getCode" :class="{'geting': count_down}">获取验证码</div>
        </div>
        <div class="input-item border-1px">
          <input type="password" class="input" v-model="pass" placeholder="设置6-18位密码">
        </div>
        <div class="input-item border-1px" v-show="!codeNeed">
          <input type="password" class="input" v-model="codeNeed" placeholder="输入邀请码">
        </div>
      </div>
      <div class="button-wrapper" @click="reg">
        <v-button :text="'注册'"></v-button>
      </div>
      <div class="button-wrapper" @click="down" style="margin-top: 10px;">
        <v-button :text="'下载'"></v-button>
      </div>
    </div>

    <!--加载框-->
    <v-toast v-show="isToast" :text="'注册中...'"></v-toast>
  </div>
</template>

<script>
  import Button from 'components/Button/Button';
  import Toast from 'components/Toast/Toast';

  const HTTP = 'http://47.52.200.172:8090/';
  const ERRORCODE = '40012';
  const STATES = 200;
  const SUCESS = '0';
  export default {
    name: 'account',
    data () {
      return {
        phone: '', // 手机号码
        reg_phone: /^1[3456789]\d{9}$/, // 匹配手机正则
        code: '', // 验证码
        codeNeed: this.$route.query.agencyNo,
        pass: '', // 密码
        default_code: 18605516920, // 默认邀请码
        count_down: 0, // 倒计时
        timer: null, // 存放定时器
        isToast: false, // 加载框
        url: ''
      }
    },
    mounted () {
      /* eslint-disable */
      let timer = setInterval(() => {
        if ( !this.url ){
          this.getUrl();
        } else {
          clearInterval(timer);
        }
      }, 1000);
    },
    methods: {
      /* eslint-disable */
      getCode (event) { // 获取验证码
        if (this.check_phone(this.phone, this.reg_phone)) {
          if (this.count_down) { // 倒计时中
            this.$layer.open({
              content: '正在获取验证码中，请勿重复获取',
              skin: 'msg',
              time: 3
            });
            return false;
          }
          // 获取验证码ajax
          let body = {
            /* eslint-disable quotes */
            'clientInfo': {
              "agentId": "gw",
              "apn": "WIFI",
              "model": this.getIA(),
              "platform": this.getIA(),
              "timestamp": 1526291601376,
              "token": "419DB8630627E9D0133B3545F2E7CCAA",
              "version": "1.0.3",
              "branch": "basic",
              "companyid": "rocket"
            },
            "command": "registerValidateCode",
            "data": {
              "mobilePhone": this.phone,
              "username": this.phone
            }
          };
          this.$axios.post(HTTP + 'lotserver/api/request?body=' + this.encrypt(JSON.stringify(body))).then((response) => {
            let pwd = this.decrypt(response.data);
            let encode = this.unzip(pwd);
            /*eslint-disable */
            if (response.status !== STATES) { // 返回状态是否正常
              // 不正常
              this.$layer.open({
                content: encode.msg,
                skin: 'msg',
                time: 3
              });
              return;
            }
            if(encode.errorcode === ERRORCODE){
              this.$layer.open({
                content: encode.msg,
                skin: 'msg',
                time: 3
              });
                return;
            }
            // 正常
            // 开始倒计时
            this.count_down = 60;
            event.target.innerHTML = `获取中(${this.count_down})s`;
            clearInterval(this.timer)
            this.timer = setInterval(() => {
              this.count_down--;
              if (this.count_down) {
                event.target.innerHTML = `获取中(${this.count_down})s`;
              } else {
                event.target.innerHTML = '获取验证码';
                clearInterval(this.timer); // 清除定时器
              }
            }, 1000);
          }).catch((e) => {
            console.log(e)
            this.$layer.open({
              content: '请求失败，请检查网络是否正常',
              skin: 'msg',
              time: 3
            });
          });
        }
      },
      reg () { // 注册账号

        if (this.check_phone(this.phone, this.reg_phone)) { // 手机号
          if (!this.code) { // 验证码
            this.$layer.open({
              content: '请输入验证码',
              skin: 'msg',
              time: 2
            });
            return false;
          }
          if (!this.check_password(this.pass.replace(/(^\s*)|(\s*$)/g, ''))) { // 密码
            // 密码验证不通过
            return false;
          }
          // 显示加载框
          this.isToast = true
          // 注册接口
          let body = {
            /* eslint-disable quotes */
            'clientInfo': {
              "agentId": "gw",
              "apn": "WIFI",
              "model": this.getIA(),
              "platform": this.getIA(),
              "timestamp": 1526291601376,
              "token": "419DB8630627E9D0133B3545F2E7CCAA",
              "version": "1.0.3",
              "branch": "basic",
              "companyid": "rocket"
            },
            "command": "newRegister",
            "data": {
              "username" : '',
              "password" : this.pass,
              "phone" : this.phone,
              "validateCode" : this.code,
              'registerType': 1,
              'invitationCode': this.codeNeed
            }
          };
          this.$axios.post(HTTP + 'lotserver/api/request?body='+ this.encrypt(JSON.stringify(body))).then((response)=>{
            let pwd = this.decrypt(response.data);
            let encode = this.unzip(pwd);
            this.isToast = false;
            if (encode.errorcode != SUCESS) {
              this.$layer.open({
                content:encode.msg ,
                skin: 'msg',
                time: 3
              });
              return
            }
            window.location.href=`//${window.location.host}/tyLotter/#/download?url=${this.url}`;
          }).catch((e)=>{
            this.isToast = false;
            this.$layer.open({
              content: '请求失败，请检查网络是否正常',
              skin: 'msg',
              time: 3
            });
          })
        }
      },
      check_phone (phone, reg) { // 验证手机号
        if (!phone) { // 没有填手机号
          this.$layer.open({
            content: '请输入手机号',
            skin: 'msg',
            time: 2
          });
          return false;
        } else if (!reg.test(phone)) {
          this.$layer.open({
            content: '请输入正确的手机号',
            skin: 'msg',
            time: 2
          });
          return false;
        }
        return true;
      },
      check_password (pass) { // 验证密码
        if (!pass) {
          this.$layer.open({
            content: '请输入密码',
            skin: 'msg',
            time: 2
          });
          return false;
        } else if (pass.match(/\s/)) {
          this.$layer.open({
            content: '密码不能含有空格',
            skin: 'msg',
            time: 2
          });
          return false;
        } else if (!this.pass.match(/^[\w\W]{6,20}$/)) {
          this.$layer.open({
            content: '密码只能是6~20位的数字、大小写字符、下划线',
            skin: 'msg',
            time: 2
          });
          return false;
        }
        return true;
      },
      encrypt (word) {
        /*eslint-disable */
        let key = CryptoJS.enc.Utf8.parse("B4F9CED935M9419D");
        let srcs = CryptoJS.enc.Utf8.parse(word);
        let encrypted = CryptoJS.AES.encrypt(srcs, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
        let encryptedStr = encrypted.ciphertext.toString();
        return encryptedStr;
      },
      decrypt (word) {
        let key = CryptoJS.enc.Utf8.parse("B4F9CED935M9419D");
        let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
        let encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
        let decrypt = CryptoJS.AES.decrypt(encryptedBase64Str, key, {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7
        });
        let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
        return decryptedStr
      },
      unzip(b64Data) {
        let strData = atob(b64Data);
        // Convert binary string to character-number array
        let charData = strData.split('').map(function(x) {
          return x.charCodeAt(0);
        });
        let binData = new Uint8Array(charData);
        var data = pako.inflate(binData);
        data = this.decodeUTF8(data)
        // Convert gunzipped byteArray back to ascii string:
        strData = JSON.parse(data);
        return strData;
      },
      decodeUTF8(arr) {
        let str = '';
        for (let i = 0; i < arr.length; i++) {
          str += String.fromCharCode(arr[i]);
        }
        return decodeURIComponent(escape(str));
      },
      // 获取下载链
      getUrl(){
        if(this.getIA() !=='android' && this.getIA() !== 'ios'){
          return false
        }
        let body = {
          /* eslint-disable quotes */
          'clientInfo': {
            "agentId": "gw",
            "apn": "WIFI",
            "model": this.getIA(),
            "platform": this.getIA(),
            "timestamp": 1526291601376,
            "token": "419DB8630627E9D0133B3545F2E7CCAA",
            "version": "1.0.3",
            "branch": "basic",
            "companyid": "rocket"
          },
          "command": "getAppDownloadRoute",
          "data": {
            "systemCode": this.getIA()
          }
        };
        this.$axios.post(HTTP + 'lotserver/api/request?body='+ this.encrypt(JSON.stringify(body))).then((response)=>{
          let pwd = this.decrypt(response.data);
          let encode = this.unzip(pwd);
          if(encode.errorcode != SUCESS){
            this.$layer.open({
              content:encode.msg ,
              skin: 'msg',
              time: 3
            });
            return
          }

          if(encode.errorcode != SUCESS) {
            this.$layer.open({
              content: encode.msg,
              skin: 'msg',
              time: 3
            });
            return
          }
          this.url = encode.data.downloadRoute;
          if (this.getIA() === 'android') {
            this.url = `//${window.location.host}/tyLotter/#/jump`;
          }

        }).catch((e)=>{
          console.log(e)
          this.$layer.open({
            content: '请求失败，请检查网络是否正常',
            skin: 'msg',
            time: 3
          });
        })
      },
      getIA(){
        let u = navigator.userAgent;
        if(u.indexOf('Android') > -1 || u.indexOf('Adr') > -1){
           return 'android'
        }else if(!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
           return 'ios'
        }

      },
      isWeixinBrowser() {
        let agent = navigator.userAgent.toLowerCase();
        if (agent.match(/MicroMessenger/i) == "micromessenger") {
          return true;
        } else {
          return false;
        }
      },
      down(){
        // if (this.isWeixinBrowser()) { // 是微信浏览器跳转到跳转中转下载页
        //   this.$router.push({
        //     path: '/jump'
        //   });
        //   return false;
        // }
        window.location.href = this.url;
      }
  },
    components: {
      vButton: Button,
      vToast: Toast
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  @import '../../common/stylus/mixin.styl'
  .account
    .header
      width: 100%;
      height: 0;
      position: relative;
      padding-top: 80%;
      img
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        width: 100%;
    .content-wrapper
      padding: 10px 20px 50px
      background: url("./bg.png") no-repeat center / 100% 100%
      .input-wrapper
        .input-item
          display: flex
          justify-content: space-between
          align-items: center
          width: 100%
          height: 60px
          border-1px-bottom(#efefef)
          .error_tip
            color: #f00
          .input
            flex: 1
            width: 84px
            height: 60px
            padding-left: 8px
            font-size: 15px
            color: #333
            &::placeholder
              color: #999
          .get-code
            flex: 0 0 99px
            width: 99px
            height: 31px
            line-height: 31px
            font-size: 15px
            text-align: center
            color: #fff
            background: linear-gradient(left, #fe3439, #ff8412);
            border-radius: 16px
            &.geting
              background: #ccc
      .button-wrapper
        margin-top: 44px

</style>
